package com.usian.service.impl;

import com.usian.mapper.*;
import com.usian.pojo.*;
import com.usian.redis.RedisClient;
import com.usian.sender.MQSender;
import com.usian.service.OrderService;
import com.usian.utils.JsonUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    TbOrderMapper tbOrderMapper;

    @Autowired
    TbOrderItemMapper tbOrderItemMapper;

    @Autowired
    TbOrderShippingMapper tbOrderShippingMapper;

    @Autowired
    TbItemMapper tbItemMapper;

    @Autowired
    RedisClient redisClient;

    @Autowired
    AmqpTemplate amqpTemplate;

    @Autowired
    LocalMessageMapper localMessageMapper;

    @Autowired
    MQSender mqSender;



    /**
     * 生成订单
     *
     * @param orderInfo
     * @return
     */
    @Override
    public Long insertOrder(OrderInfo orderInfo) {

        long orderId = redisClient.incr("ORDER_ID_KEY", 1L);
        //1、解析orderInfo
        String orderItem = orderInfo.getOrderItem();
        TbOrderShipping tbOrderShipping = orderInfo.getTbOrderShipping();
        List<TbOrderItem> tbOrderItems = JsonUtils.jsonToList(orderItem, TbOrderItem.class);
        TbOrder tbOrder = orderInfo.getTbOrder();

        //2、保存订单信息
        tbOrder.setOrderId(orderId + "");
        tbOrder.setCreateTime(new Date());
        tbOrder.setUpdateTime(new Date());
        tbOrder.setStatus(1);
        tbOrderMapper.insertSelective(tbOrder);

        //3、保存明细信息
        for (TbOrderItem tbOrderItem : tbOrderItems) {
            long orderItemId = redisClient.incr("ORDER_ITEM_ID_KEY", 1L);
            tbOrderItem.setOrderId(orderId + "");
            tbOrderItem.setId(orderItemId + "");
            tbOrderItemMapper.insertSelective(tbOrderItem);
        }

        //4、保存物流信息
        tbOrderShipping.setCreated(new Date());
        tbOrderShipping.setUpdated(new Date());
        tbOrderShipping.setOrderId(orderId + "");
        tbOrderShippingMapper.insertSelective(tbOrderShipping);

        //分布式事务扣减库存 存入本地消息记录表
        LocalMessage localMessage = new LocalMessage();
        String tx_no = UUID.randomUUID().toString();
        localMessage.setTxNo(tx_no);
        localMessage.setOrderNo(orderId + "");
        localMessage.setState(0);
        localMessageMapper.insertSelective(localMessage);

        //发布消息到mq，完成扣减仓库
        mqSender.sendMsg(localMessage);
        //发布消息到mq，完成扣减仓库
        //amqpTemplate.convertAndSend("order_exchange", "order.add", orderId);

        //5、返回订单id
        return orderId;
    }

    /**
     * 查询超时订单
     *
     * @return
     */
    @Override
    public List<TbOrder> selectOvertimeOrder() {
        return tbOrderMapper.selectOvertimeOrder();
    }

    /**
     * 关闭超时订单
     *
     * @param tbOrder
     */
    @Override
    public void updateOverTimeTbOrder(TbOrder tbOrder) {
        //1、未付款，2、已付款，3、未发货，4、已发货，5、交易成功，6、交易关闭
        tbOrder.setStatus(6);
        tbOrder.setUpdateTime(new Date());
        tbOrder.setCloseTime(new Date());
        tbOrder.setEndTime(new Date());
        tbOrderMapper.updateByPrimaryKeySelective(tbOrder);
    }

    /**
     * 把超时订单的商品库存加回去
     *
     * @param orderId
     */
    @Override
    public void updateTbItemByOrderId(String orderId) {
        TbOrderItemExample tbOrderItemExample = new TbOrderItemExample();
        TbOrderItemExample.Criteria criteria = tbOrderItemExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<TbOrderItem> tbOrderItems = tbOrderItemMapper.selectByExample(tbOrderItemExample);
        for (TbOrderItem tbOrderItem : tbOrderItems) {
            //修改商品库存
            TbItem item = tbItemMapper.selectByPrimaryKey(Long.valueOf(tbOrderItem.getId()));
            item.setNum(item.getNum() + tbOrderItem.getNum());
            tbItemMapper.updateByPrimaryKeySelective(item);
        }
    }
}
